// https://leetcode.cn/problems/balanced-binary-tree/
// Created by ade on 2022/7/19.

// 给定一个二叉树，判断它是否是高度平衡的二叉树。
// 本题中，一棵高度平衡二叉树定义为：
// 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

#include <iostream>
#include <vector>


using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    bool flag = true;

    bool isBalanced(TreeNode *root) {
        dfs(root);
        return flag;
    }

    int getHeight(TreeNode *root) {
        if (root) {
            return max(getHeight(root->left), getHeight(root->right)) + 1;
        }
        return 0;
    }

    void dfs(TreeNode *root) {
        if(abs(getHeight(root->left) - getHeight(root->right)) > 1){
            flag = false;
            return;
        }
        dfs(root->left);
        dfs(root->right);
    }

    TreeNode *init() {
        // [1,2,2,3,3,null,null,4,4]
        TreeNode *head1 = new TreeNode(1);
        TreeNode *head2 = new TreeNode(2);
        TreeNode *head3 = new TreeNode(2);
        TreeNode *head4 = new TreeNode(3);
        TreeNode *head5 = new TreeNode(3);
        TreeNode *head6 = new TreeNode(4);
        TreeNode *head7 = new TreeNode(4);
        head1->left = head2;
        head1->right = head3;
        head2->left = head4;
        head2->right = head4;
        head3->left = nullptr;
        head3->right = nullptr;
        head4->left = head6;
        head4->right = head6;
        return head1;
    }
};

int main() {
    Solution so;
    TreeNode *head = so.init();
    auto res = so.isBalanced(head);
    if (res) {
        cout << "yes" << endl;
    } else {
        cout << "no" << endl;
    }
    return 0;
}